import db from '../database.js';

// 获取所有章节（管理端显示全部，用户端过滤隐藏的）
export const getAllChapters = (req, res) => {
  try {
    const { admin } = req.query;
    let query = 'SELECT * FROM chapters';
    
    // 用户端只显示未隐藏的章节
    if (!admin) {
      query += ' WHERE is_hidden = 0';
    }
    
    query += ' ORDER BY order_num';
    
    const chapters = db.prepare(query).all();
    res.json(chapters);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 获取单个章节
export const getChapterById = (req, res) => {
  try {
    const chapter = db.prepare('SELECT * FROM chapters WHERE id = ?').get(req.params.id);
    if (!chapter) {
      return res.status(404).json({ error: '章节不存在' });
    }
    res.json(chapter);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 创建章节（需要认证）
export const createChapter = (req, res) => {
  try {
    const { title, order_num, is_hidden } = req.body;
    if (!title || order_num === undefined) {
      return res.status(400).json({ error: '缺少必要字段' });
    }
    
    const result = db.prepare(`
      INSERT INTO chapters (title, order_num, is_hidden) 
      VALUES (?, ?, ?)
    `).run(title, order_num, is_hidden ? 1 : 0);
    
    const newChapter = db.prepare('SELECT * FROM chapters WHERE id = ?').get(result.lastInsertRowid);
    res.status(201).json(newChapter);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 更新章节（需要认证）
export const updateChapter = (req, res) => {
  try {
    const { title, order_num, is_hidden } = req.body;
    
    const result = db.prepare(`
      UPDATE chapters 
      SET title = COALESCE(?, title),
          order_num = COALESCE(?, order_num),
          is_hidden = COALESCE(?, is_hidden),
          updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `).run(
      title, 
      order_num, 
      is_hidden !== undefined ? (is_hidden ? 1 : 0) : null,
      req.params.id
    );
    
    if (result.changes === 0) {
      return res.status(404).json({ error: '章节不存在' });
    }
    
    const updatedChapter = db.prepare('SELECT * FROM chapters WHERE id = ?').get(req.params.id);
    res.json(updatedChapter);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 删除章节（需要认证）
export const deleteChapter = (req, res) => {
  try {
    const result = db.prepare('DELETE FROM chapters WHERE id = ?').run(req.params.id);
    if (result.changes === 0) {
      return res.status(404).json({ error: '章节不存在' });
    }
    res.json({ message: '章节已删除' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

